package hanjia;

/**
 * Description:
 * Author:    Dane
 * CreateTime:2025/1/19-下午6:01
 * Since  :   1.0
 * Version:   1.0
 */
public class DoubleLinkedListSentinel {

    private Node head;
    private Node tail;

    private static class Node {
        Node pre;
        Node next;
        int value;

        public Node(Node pre, Node next, int value) {
            this.pre = pre;
            this.next = next;
            this.value = value;
        }
    }

    public DoubleLinkedListSentinel() {
        this.head = new Node(null, null, 666);
        this.tail = new Node(null, null, 777);
        head.next = tail;
        tail.pre = head;
    }

    private Node findNode(int index) {
        int i = -1;
        Node temp = head;
        while (temp != tail) {
            if (i == index) {
                return temp;
            }
            temp = temp.next;
            i++;
        }
        return null;
    }

    public void insert(int index, int value) {
        Node pre = findNode(index - 1);

        if (pre == null) {
            throw new RuntimeException();
        }
        Node next = pre.next;
        Node current = new Node(pre, next, value);
        pre.next = current;
        next.pre = current;
    }

    public void addFirst(int value) {
        insert(0, value);
    }

    public void remove(int index) {
        if (index < 0) {
            throw new RuntimeException();
        }

        Node now = findNode(index);
        if (now == null) {
            throw new RuntimeException();
        }


        Node pre = now.pre;
        Node next = now.next;
        pre.next = next;
        next.pre = pre;

    }

    public void addLast(int value) {
        Node pre = tail.pre;
        Node now = new Node(pre, tail, value);
        pre.next=now;
        tail.pre=now;


    }

    public void removeLast(){
        Node pre = tail.pre;
        if (pre==head) {
            throw  new RuntimeException();
        }

        Node morePre=pre.pre;
        morePre.next=tail;
        tail.pre=morePre;

    }


}
